import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:leader_help/global/user/logic.dart';
import 'package:leader_help/page/tab_controller/controller.dart';
import 'package:leader_help/utils/httputils/api.dart';
import 'package:leader_help/utils/httputils/httpmanager.dart';
import 'package:leader_help/utils/httputils/resultdata.dart';
import 'package:leader_help/utils/storage.dart';
import 'package:leader_help/utils/util.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import 'index.dart';

class LoginController extends GetxController
    with GetSingleTickerProviderStateMixin {
  LoginController();
  final userCtrl = Get.find<UserController>();
  final mainCtrl = Get.find<TbController>();
  final state = LoginState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.tabCtrl = TabController(length: 2, vsync: this)
      ..addListener(() {
        if (state.tabCtrl.indexIsChanging) {
          if (state.tabCtrl.previousIndex != state.tabCtrl.index) {
            update();
          }
        }
      });
  }

  void actionLogin() async {
    mainCtrl.state.isShowFloat = true;
    Get.back();
    if (state.accountCtrl.text.toString().trim().isEmpty) {
      return EasyLoading.showToast('请输入账号');
    }
    if (state.pwdCtrl.text.toString().trim().isEmpty) {
      return EasyLoading.showToast('请输入有效密码');
    }
    var map = {
      "loginName": state.accountCtrl.text.toString(),
      "loginPassword": state.pwdCtrl.text.toString(),
      "loginType": 1,
      "appCode": "jx-clivil-servant-assessment"
    };

    ResultData response = await Api.login(map);

    if (response.isSuccess) {
      userCtrl.configUser(response.data);

      // await SpUtil().setStr('userName', PasswordloginState.userinfo!.userName!);
      await SpUtil().setJSON('userInfo', response.data);
      await SpUtil().setStr('phone', state.accountCtrl.text.toString());

      Get.defaultDialog(
          title: '请求信息',
          middleText: response.data.toString(),
          middleTextStyle: TextStyle(fontSize: 11.sp));
    }
  }

  void actionWxlogin() async {
    WXUtil().login();
  }

  void actionApplelogin() async {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
      webAuthenticationOptions: WebAuthenticationOptions(
        // TODO: Set the `clientId` and `redirectUri` arguments to the values you entered in the Apple Developer portal during the setup
        clientId: 'de.lunaone.flutter.signinwithappleexample.service',

        redirectUri:
            // For web your redirect URI needs to be the host of the "current page",
            // while for Android you will be using the API server that redirects back into your app via a deep link
            Uri.parse(
          'https://flutter-sign-in-with-apple-example.glitch.me/callbacks/sign_in_with_apple',
        ),
      ),
      // TODO: Remove these if you have no need for them
      nonce: 'example-nonce',
      state: 'example-state',
    );

    // ignore: avoid_print
    print(credential);

    // This is the endpoint that will convert an authorization code obtained
    // via Sign in with Apple into a session in your system
    final signInWithAppleEndpoint = Uri(
      scheme: 'https',
      host: 'flutter-sign-in-with-apple-example.glitch.me',
      path: '/sign_in_with_apple',
      queryParameters: <String, String>{
        'code': credential.authorizationCode,
        if (credential.givenName != null) 'firstName': credential.givenName!,
        if (credential.familyName != null) 'lastName': credential.familyName!,
        'useBundleId': GetPlatform.isIOS ? 'true' : 'false',
        if (credential.state != null) 'state': credential.state!,
      },
    );

    final session = await HttpManager().post(signInWithAppleEndpoint);
    // If we got this far, a session based on the Apple ID credential has been created in your system,
    // and you can now set this as the app's session
    // ignore: avoid_print
    print(session);
  }

  void actionHelp() {}
  void actionPrivacy() {}
  void actionForget() {
    Get.toNamed(RouterPath.forgot_pwd);
  }

  void actionRegister() {
    Get.toNamed(RouterPath.register);
  }

  void actionTerms() {}

  void handleTap(int index) {
    if (index == 0) {
      actionHelp();
    } else if (index == 1) {
      actionPrivacy();
    } else if (index == 2) {
      actionTerms();
    }
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    userCtrl.isAtLogin = false;
    mainCtrl.state.isShowFloat = false;
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
